package com.example.finalsystem.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.finalsystem.Entity.Deal;
import com.example.finalsystem.Entity.ListGoods;
import com.example.finalsystem.Service.ClientService;
import com.example.finalsystem.Service.DealService;
import com.example.finalsystem.Service.ListGoodsService;
import com.example.finalsystem.Service.MemberService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DealController {
    @Autowired
    MemberService memberService;
    @Autowired
    DealService dealService;
    @Autowired
    ClientService clientService;
    @Autowired
    ListGoodsService listGoodsService;

    @ResponseBody
    @PostMapping("/deal/getDealByStaff")
    public String getDealByStaff(@RequestParam String userId)
    {
        System.out.println("前端传来的id："+userId);
        SqlSession sqlSession =openSession();
        String str =JSONArray.toJSONString(   dealService.findDealByStaffId(userId,sqlSession));
        sqlSession.close();
        return str;
    }

    @ResponseBody
    @PostMapping("/deal/getSale")
    public  String getSale()
    {
        SqlSession sqlSession = openSession();
        double sale = 0;
        for (Deal d:dealService.getAllDeal(sqlSession)
             ) {
            for (ListGoods l:listGoodsService.getListGoodsByDealId(d.getDealid(),sqlSession)
                 ) {
                sale+= l.getGoodsprice()*l.getGoodsnumber();
            }
        }
        sqlSession.close();
        return sale+"";
    }



    @ResponseBody
    @PostMapping("/deal/addDeal")
    public String addDeal(@RequestParam String userId,@RequestParam Long clientId,@RequestParam String content,@RequestParam String goods,@RequestParam Long signTime)
    {

        try
        {
            Date sign = new Timestamp(signTime);
            String dealId =  dealService.addDeal(userId,clientId,content,sign);
            return listGoodsService.addListGoods(dealId,goods);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "添加失败";
    }
//    查询合同
//  返回 goods(货物清单) ， message（合同信息）
    @ResponseBody
    @PostMapping("/deal/getDeal")
    public String getDeal(@RequestParam String dealId)
    {
        SqlSession sqlSession = openSession();
        Map<String,Object> map = new HashMap<>();
        map.put("message",dealService.getDeal(dealId));
        map.put("goods",listGoodsService.getListGoodsByDealId(dealId,sqlSession));
        sqlSession.close();
        return JSONObject.toJSONString(map);
    }

    @ResponseBody
    @PostMapping("/deal/fixdeal")
    public String fixDeal(@RequestParam String dealId,@RequestParam String userId,@RequestParam Long clientId,@RequestParam String content,@RequestParam String goods,@RequestParam Long signTime)
    {
        System.out.println("content: "+content);
        try
        {
            Date sign = new Timestamp(signTime);
            dealService.fixDeal(dealId,userId,clientId,content,sign);
            listGoodsService.deleteAllByDealId(dealId);
            return listGoodsService.addListGoods(dealId,goods).equals("添加成功")?"修改成功":"修改失败";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "修改失败";
    }










    //    添加合同货物信息
    @ResponseBody
    @PostMapping("/deal/addDealGoods")
    public String addDealGoods(@RequestParam String dealId,@RequestParam String good)
    {
        if (dealService.getDeal(dealId)== null)
        {
            return "添加失败，没有找到合同";
        }
        listGoodsService.addListGoods(dealId,good);
        return "添加成功";
    }


// 修改合同信息
    @ResponseBody
    @PostMapping("/deal/fixDealMessage")
    public String fixDealMessage(@RequestParam String dealId,@RequestParam String userId,@RequestParam Long clientId,@RequestParam String content,@RequestParam String signTime)
    {
        SimpleDateFormat formatfortime = new SimpleDateFormat("yyyy-MM-dd");

        try
        {
            Date sign = formatfortime.parse(signTime);
            return  dealService.fixDeal(dealId,userId,clientId,content,sign);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "修改失败";

    }
//    修改货物信息
    @ResponseBody
    @PostMapping("/deal/fixDealGoods")
    public String fixDealGoods(@RequestParam Long listGoodsId,@RequestParam double goodsPrice,@RequestParam int goodsNumber,@RequestParam String goodsName)
    {
        return listGoodsService.fixListGoodsById(listGoodsId,goodsNumber,goodsPrice,goodsName);
    }
//    删除合同 对应删除合同下的货物清单
 @ResponseBody
    @PostMapping("/deal/deleteDeal")
    public String deleteDeal(@RequestParam String dealId)
    {
        return  dealService.deleteDeal(dealId);
    }

    //    删除某个货物单
    @ResponseBody
    @PostMapping("/deal/deleteDealGoods")
    public String deleteDealGoods(@RequestParam Long listGoodsId)
    {
        return  listGoodsService.deleteByListGoodsId(listGoodsId);
    }
//    以下是分页合同信息所需功能
//    获取合同总数
    @ResponseBody
    @PostMapping("/deal/countDeal")
    public String countDeal()
    {
        return dealService.countDeal()+"";
    }

//    获取合同的分页信息
    @ResponseBody
    @PostMapping("/deal/getListOfDeal")
    public String getListOfDeal(@RequestParam int currentPage,@RequestParam int pageSize)
    {

        List<Deal> deals = dealService.getListOfDeal((currentPage-1)*pageSize,pageSize);
        SqlSession sqlSession = openSession();
        for (Deal d: deals) {
            d.setCanFix(dealService.canFix(d.getDealid(),sqlSession));
        }
        sqlSession.close();
        return JSONArray.toJSONString(deals);
    }
    @ResponseBody
    @PostMapping("/deal/getAllDeal")
    public String getAllDeal()
    {
        SqlSession sqlSession =openSession();
        String str = JSONArray.toJSONString(dealService.getAllDeal(sqlSession));
        sqlSession.close();
        return str;
    }

    @PostMapping("/deal/getAllListGoods")
    @ResponseBody
    public String getAllListGoodsByListId(@RequestParam String dealId)
    {
        SqlSession sqlSession = openSession();
        String str =JSONArray.toJSONString(listGoodsService.getListGoodsByDealId(dealId,sqlSession));
        sqlSession.close();
        return    str;
    }

    private SqlSession openSession()
    {
        String resource = "mybatis-config.xml";
        InputStream is = DealController.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        return   sessionFactory.openSession(true);
//        return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    }
}
